export default {
  namespaced: true,
  state: {
    Carts: [],
  },
  mutations: {
    SET_CART(state, paylode) {
      // console.log(paylode.id)
      let target = state.Carts.find((i) => i.id === paylode.id);
      if (!target) {
        let obj = {
          title: paylode.title,
          price: paylode.price,
          inventory: paylode.inventory,
          count: 1,
          id: paylode.id,
        };
        state.Carts.push(obj);
      } else {
        target.count++;
      }
      // state.Carts = paylode
      // state.Carts.push(paylode)
    },
    REMOVE_CART(state, paylode) {
      let target = state.Carts.find((m) => m.id === paylode.id);
      if (target) {
        target.count--;
      }
      if (target.count === 0) {
        state.Carts = state.Carts.filter((item) => item.id !== target.id);
      }
    },
  },
  actions: {
    ADD_CART(context, paylode) {
      context.commit("SET_CART", paylode);
      //   context.commit("ADD_PRODUCT", paylode);
      context.commit("Products/SET_PRODUCT", paylode.id, { root: true });
    },
    CART_REMOVE(context, paylode) {
      context.commit("REMOVE_CART", paylode);
    },
  },
  getters: {
    total(state) {
      return state.Carts.reduce((total, item) => {
        return (total += item.price * item.count);
      }, 0).toFixed(2);
    },
  },
  modules: {},
};
